import numpy as np

def demonstrate_numpy_statistical_functions():
    """
    NumPy统计函数演示脚本
    包含菜鸟教程链接中的所有统计函数知识点
    """
    
    print("=== NumPy统计函数演示 ===\n")
    
    # 创建测试数组
    test_array_2d = np.array([[3, 7, 5], 
                              [8, 4, 3], 
                              [2, 4, 9]])
    
    test_array_1d = np.array([1, 2, 3, 4])
    
    print("测试数组:")
    print(f"二维数组:\n{test_array_2d}")
    print(f"一维数组: {test_array_1d}\n")
    
    # 1. numpy.amin() - 最小值函数
    print("1. amin() - 最小值函数")
    print("=" * 50)
    
    print("整个数组的最小值:")
    min_all = np.amin(test_array_2d)
    print(f"np.amin(array) = {min_all}")
    
    print("\n沿轴1（每行）的最小值:")
    min_axis1 = np.amin(test_array_2d, axis=1)
    print(f"np.amin(array, axis=1) = {min_axis1}")
    
    print("沿轴0（每列）的最小值:")
    min_axis0 = np.amin(test_array_2d, axis=0)
    print(f"np.amin(array, axis=0) = {min_axis0}")
    
    # 2. numpy.amax() - 最大值函数
    print("\n2. amax() - 最大值函数")
    print("=" * 50)
    
    print("整个数组的最大值:")
    max_all = np.amax(test_array_2d)
    print(f"np.amax(array) = {max_all}")
    
    print("\n沿轴1（每行）的最大值:")
    max_axis1 = np.amax(test_array_2d, axis=1)
    print(f"np.amax(array, axis=1) = {max_axis1}")
    
    print("沿轴0（每列）的最大值:")
    max_axis0 = np.amax(test_array_2d, axis=0)
    print(f"np.amax(array, axis=0) = {max_axis0}")
    
    # 3. numpy.ptp() - 峰峰值函数（最大值-最小值）
    print("\n3. ptp() - 峰峰值函数（最大值-最小值）")
    print("=" * 50)
    
    print("整个数组的峰峰值:")
    ptp_all = np.ptp(test_array_2d)
    print(f"np.ptp(array) = {ptp_all}")
    
    print("\n沿轴1（每行）的峰峰值:")
    ptp_axis1 = np.ptp(test_array_2d, axis=1)
    print(f"np.ptp(array, axis=1) = {ptp_axis1}")
    
    print("沿轴0（每列）的峰峰值:")
    ptp_axis0 = np.ptp(test_array_2d, axis=0)
    print(f"np.ptp(array, axis=0) = {ptp_axis0}")
    
    # 4. numpy.percentile() - 百分位数函数
    print("\n4. percentile() - 百分位数函数")
    print("=" * 50)
    
    percentile_array = np.array([[10, 7, 4], 
                                [3, 2, 1]])
    
    print(f"百分位数测试数组:\n{percentile_array}")
    
    print("\n50%分位数（中位数）:")
    p50 = np.percentile(percentile_array, 50)
    print(f"np.percentile(array, 50) = {p50}")
    
    print("\n沿轴0（每列）的50%分位数:")
    p50_axis0 = np.percentile(percentile_array, 50, axis=0)
    print(f"np.percentile(array, 50, axis=0) = {p50_axis0}")
    
    print("沿轴1（每行）的50%分位数:")
    p50_axis1 = np.percentile(percentile_array, 50, axis=1)
    print(f"np.percentile(array, 50, axis=1) = {p50_axis1}")
    
    print("\n多个百分位数计算:")
    percentiles = np.percentile(percentile_array, [25, 50, 75])
    print(f"25%, 50%, 75%分位数: {percentiles}")
    
    # 5. numpy.median() - 中位数函数
    print("\n5. median() - 中位数函数")
    print("=" * 50)
    
    median_array = np.array([[30, 65, 70], 
                            [80, 95, 10], 
                            [50, 90, 60]])
    
    print(f"中位数测试数组:\n{median_array}")
    
    print("\n整个数组的中位数:")
    median_all = np.median(median_array)
    print(f"np.median(array) = {median_all}")
    
    print("\n沿轴0（每列）的中位数:")
    median_axis0 = np.median(median_array, axis=0)
    print(f"np.median(array, axis=0) = {median_axis0}")
    
    print("沿轴1（每行）的中位数:")
    median_axis1 = np.median(median_array, axis=1)
    print(f"np.median(array, axis=1) = {median_axis1}")
    
    # 6. numpy.mean() - 平均值函数
    print("\n6. mean() - 平均值函数")
    print("=" * 50)
    
    mean_array = np.array([[1, 2, 3], 
                          [3, 4, 5], 
                          [4, 5, 6]])
    
    print(f"平均值测试数组:\n{mean_array}")
    
    print("\n整个数组的平均值:")
    mean_all = np.mean(mean_array)
    print(f"np.mean(array) = {mean_all}")
    
    print("\n沿轴0（每列）的平均值:")
    mean_axis0 = np.mean(mean_array, axis=0)
    print(f"np.mean(array, axis=0) = {mean_axis0}")
    
    print("沿轴1（每行）的平均值:")
    mean_axis1 = np.mean(mean_array, axis=1)
    print(f"np.mean(array, axis=1) = {mean_axis1}")
    
    # 7. numpy.average() - 加权平均值函数
    print("\n7. average() - 加权平均值函数")
    print("=" * 50)
    
    print("一维数组的简单平均值:")
    avg_simple = np.average(test_array_1d)
    print(f"np.average({test_array_1d}) = {avg_simple}")
    
    print("\n带权重的加权平均值:")
    weights = np.array([4, 3, 2, 1])
    avg_weighted = np.average(test_array_1d, weights=weights)
    print(f"权重: {weights}")
    print(f"np.average(array, weights=weights) = {avg_weighted}")
    
    print("\n返回加权平均值和权重总和:")
    avg_with_sum = np.average(test_array_1d, weights=weights, returned=True)
    print(f"np.average(array, weights=weights, returned=True) = {avg_with_sum}")
    
    # 二维数组加权平均
    print("\n二维数组加权平均:")
    array_2d_weighted = np.arange(6).reshape(3, 2)
    weights_2d = np.array([3, 5])
    print(f"二维数组:\n{array_2d_weighted}")
    print(f"权重: {weights_2d}")
    
    avg_2d = np.average(array_2d_weighted, axis=1, weights=weights_2d)
    print(f"沿轴1的加权平均: {avg_2d}")
    
    # 8. 标准差和方差
    print("\n8. 标准差和方差函数")
    print("=" * 50)
    
    print("标准差计算:")
    std_result = np.std(test_array_1d)
    print(f"np.std({test_array_1d}) = {std_result}")
    
    print("\n方差计算:")
    var_result = np.var(test_array_1d)
    print(f"np.var({test_array_1d}) = {var_result}")
    
    # 手动验证标准差和方差
    print("\n手动验证标准差和方差:")
    mean_val = np.mean(test_array_1d)
    deviations = test_array_1d - mean_val
    squared_deviations = deviations ** 2
    variance_manual = np.mean(squared_deviations)
    std_manual = np.sqrt(variance_manual)
    
    print(f"平均值: {mean_val}")
    print(f"偏差: {deviations}")
    print(f"偏差平方: {squared_deviations}")
    print(f"手动计算方差: {variance_manual}")
    print(f"手动计算标准差: {std_manual}")
    
    print("\n=== 基本统计函数演示结束 ===\n")

def demonstrate_advanced_statistical_functions():
    """
    高级统计函数演示（补充内容）
    """
    print("=== 高级统计函数补充演示 ===")
    print("=" * 50)
    
    # 创建测试数据
    data = np.array([[1, 2, 3, 4, 5],
                    [6, 7, 8, 9, 10],
                    [11, 12, 13, 14, 15]])
    
    print(f"测试数据:\n{data}")
    
    # 9. 其他统计函数
    print("\n9. 其他统计函数")
    print("-" * 30)
    
    # 求和
    print("求和函数:")
    print(f"总和: np.sum(data) = {np.sum(data)}")
    print(f"每列和: np.sum(data, axis=0) = {np.sum(data, axis=0)}")
    print(f"每行和: np.sum(data, axis=1) = {np.sum(data, axis=1)}")
    
    # 累积和
    print("\n累积和函数:")
    print(f"累积和: np.cumsum(data) = {np.cumsum(data)}")
    
    # 乘积
    print("\n乘积函数:")
    print(f"总乘积: np.prod(data) = {np.prod(data)}")
    print(f"每列乘积: np.prod(data, axis=0) = {np.prod(data, axis=0)}")
    
    # 累积乘积
    print("\n累积乘积函数:")
    print(f"累积乘积: np.cumprod(data) = {np.cumprod(data)}")
    
    # 10. 统计函数的高级参数
    print("\n10. 统计函数的高级参数")
    print("-" * 30)
    
    # keepdims参数
    print("keepdims参数演示:")
    mean_no_keep = np.mean(data, axis=0)
    mean_keep = np.mean(data, axis=0, keepdims=True)
    
    print(f"不保持维度: shape={mean_no_keep.shape}, 值={mean_no_keep}")
    print(f"保持维度: shape={mean_keep.shape}, 值=\n{mean_keep}")
    
    # where参数
    print("\nwhere参数演示（条件统计）:")
    condition = data > 5
    mean_conditional = np.mean(data, where=condition)
    print(f"条件: data > 5")
    print(f"满足条件的元素平均值: {mean_conditional}")
    
    # 11. 相关系数和协方差
    print("\n11. 相关系数和协方差")
    print("-" * 30)
    
    x = np.array([1, 2, 3, 4, 5])
    y = np.array([2, 4, 6, 8, 10])
    
    print(f"数组x: {x}")
    print(f"数组y: {y}")
    
    correlation = np.corrcoef(x, y)[0, 1]
    covariance = np.cov(x, y)[0, 1]
    
    print(f"相关系数: {correlation}")
    print(f"协方差: {covariance}")
    
    # 12. 直方图统计
    print("\n12. 直方图统计")
    print("-" * 30)
    
    hist_data = np.array([1, 2, 2, 3, 3, 3, 4, 4, 5])
    hist, bin_edges = np.histogram(hist_data, bins=5)
    
    print(f"数据: {hist_data}")
    print(f"直方图计数: {hist}")
    print(f"边界: {bin_edges}")
    
    print("\n=== 高级统计演示结束 ===")

def demonstrate_statistical_edge_cases():
    """
    统计函数的边界情况演示
    """
    print("\n=== 统计函数边界情况演示 ===")
    print("=" * 50)
    
    # 空数组
    print("1. 空数组处理:")
    empty_array = np.array([])
    try:
        result = np.mean(empty_array)
        print(f"空数组平均值: {result}")
    except Exception as e:
        print(f"错误: {e}")
    
    # 包含NaN的数组
    print("\n2. NaN值处理:")
    nan_array = np.array([1, 2, np.nan, 4, 5])
    print(f"包含NaN的数组: {nan_array}")
    
    # 使用nanmean等函数处理NaN
    mean_with_nan = np.nanmean(nan_array)
    print(f"忽略NaN的平均值 (np.nanmean): {mean_with_nan}")
    
    # 无穷大值处理
    print("\n3. 无穷大值处理:")
    inf_array = np.array([1, 2, np.inf, 4, 5])
    print(f"包含无穷大的数组: {inf_array}")
    
    try:
        mean_inf = np.mean(inf_array)
        print(f"包含无穷大的平均值: {mean_inf}")
    except Exception as e:
        print(f"错误: {e}")
    
    # 大数据集统计
    print("\n4. 大数据集统计演示:")
    large_data = np.random.normal(100, 15, 10000)  # 正态分布，均值100，标准差15
    print(f"大数据集统计:")
    print(f"样本大小: {len(large_data)}")
    print(f"均值: {np.mean(large_data):.2f}")
    print(f"标准差: {np.std(large_data):.2f}")
    print(f"中位数: {np.median(large_data):.2f}")
    
    print("\n=== 边界情况演示结束 ===")

if __name__ == "__main__":
    demonstrate_numpy_statistical_functions()
    demonstrate_advanced_statistical_functions()
    demonstrate_statistical_edge_cases()